<template>
  <div class="container" @touchstart.stop @touchmove.stop :class="{'isNewTab': isNewTab&&!inputfocus,'isIphoneX':isIphoneX&&!inputfocus}">
    <div class="class-iphone">
      <keep-alive>
        <router-view v-if="$route.meta.keepAlive"></router-view>
      </keep-alive>
      <router-view v-if="!$route.meta.keepAlive"></router-view>
    </div>
  </div>
</template>

<script>
import { mapState , mapGetters } from 'vuex'
import { translateGroupSystemNotice } from './utils/common'
import { ACTION } from './utils/trtcCustomMessageMap'
import MTA from './utils/mta'
import { apiGetsig , getbaseTime , apiGetGroupList , apiGetC2CList , apiJsSdkSign , apiplanprocess } from '@/api/im/api'
import basePath from '@/api/api.js'
import { changetime } from '@/utils/date'
import wx from 'weixin-js-sdk'


export default {
  title: 'imweb',
  data() {
    return {
      cookuserID: '',
      cookuserSig: '',
      token: '',
      profileId: '',
      isNewTab: false,
      isIphoneX: false,
    }
  },

  computed: {
    ...mapState({
      currentUserProfile: state => state.user.currentUserProfile,
      currentConversation: state => state.conversation.currentConversation,
      isLogin: state => state.user.isLogin,
      isSDKReady: state => state.user.isSDKReady,
      isBusy: state => state.video.isBusy,
      userID: state => state.user.userID,
      exportType: state => state.user.exportType,
      servicemsgId: state => state.conversation.servicemsgId,
      servicemsgId02: state => state.conversation.servicemsgId02,
      userDinfo: state => state.user.userDinfo,
      cwiappid: state => state.user.cwiappid,
      nowtime: state => state.user.nowtime,
      inputfocus: state => state.conversation.inputfocus,
      conversationList: state => state.conversation.conversationList
    }),
    ...mapGetters(['toAccount']),
    // 是否显示 Loading 状态
    showLoading() {
      return !this.isSDKReady
    }
  },
  created() {
    console.log(location.href)
    var self = this;
    self.fnJsSdkSign();
    //自动更新系统时间
    setInterval(function(){
      self.$store.commit('upNowtime',getbaseTime(1))
    },60000)
    //结束
    if(this.$route.query.appid){
      this.$store.commit('upCwiappid',this.$route.query.appid)
    }else{
        
      if(basePath.ENV == 'test'){
        this.$store.commit('upCwiappid',311001)
      }else{
        this.$store.commit('upCwiappid',311001)
      }
    }

    
    this.token = this.$route.query.token || this.$getCookie('token') || ''
    this.profileId = this.$route.query.profileid || this.$getCookie('profileId') || ''
    this.isNewTab = this.$route.query.isNewTab || false
    this.isIphoneX = this.$route.query.isIphoneX || false
    this.$setCookie('token',this.token)
    this.$setCookie('profileId',this.profileId)
    
    this.cookuserID = this.$route.query.userid || ''
    this.cookuserSig = this.$route.query.usersig || ''
    this.$setCookie('userID',this.cookuserID)
    this.$setCookie('userSig',this.cookuserSig)


    console.log('query',this.$route.query);
    console.log('token',this.token);
    console.log('profileId',this.profileId);


    //测试
    // this.token = '1fd983323ad51ae660814ac16645fbf1';
    // this.profileId = '1249';
    // this.cookuserID = '311001_225949195';

    // this.$setCookie('userID',this.cookuserID)
    // this.$setCookie('userSig',this.cookuserSig)
    // this.$setCookie('token',this.token)
    // this.$setCookie('profileId',this.profileId)
    //-------------------


    if(this.cookuserID&&this.cookuserSig){
      self.tokenlogin(this.cookuserID,this.cookuserSig)
    }else if(this.$route.query.noim==1){
      
    }else if(this.token&&this.profileId){
      this.fnCwiLogin()
    }
    this.$store.commit('upExportType',1)
    // 初始化监听器
    if(this.$route.query.noim==1){
      this.$store.commit('uploadNohasim',1)
    }else{
      this.$store.commit('uploadNohasim','')
      this.initListener();
      // this.fnmessageConversation(this.$route.query.type,this.$route.query.ugid)
    }
  },
  mounted() {
    var self = this;
    setTimeout(function(){
      self.isNewTab = self.$route.query.isNewTab || false
      self.isIphoneX = self.$route.query.isIphoneX || false
    },3000)
  },
  activated(){
    this.isNewTab = this.$route.query.isNewTab || false
    this.isIphoneX = this.$route.query.isIphoneX || false
  },
  watch: {
    isLogin(next) {
      if (next) {
        MTA.clickStat('link_two', { show: 'true' })
      }
    }
  },

  methods: {
    //微信配置
    fnJsSdkSign(){
      var self = this;
      apiJsSdkSign({
        url: encodeURIComponent(location.href.split('#')[0])
      }).then(res => {
        // self.$store.commit('uploadweixinsdk',res)
        const response = res.data
        console.log('--server--',response)
        wx.config({
          debug: false,
          appId: response.wx_app_id,
          timestamp: response.timestamp,
          nonceStr: response.nonce_str,
          signature: response.signature,
          jsApiList: [
            'onMenuShareTimeline',
            'onMenuShareAppMessage',
            'onMenuShareQQ',
            'onMenuShareWeibo',
            'onMenuShareQZone',
            'startRecord',
            'stopRecord',
            'onVoiceRecordEnd',
            'playVoice',
            'pauseVoice',
            'stopVoice',
            'onVoicePlayEnd',
            'uploadVoice',
            'downloadVoice',
            'chooseImage',
            'previewImage',
            'uploadImage',
            'downloadImage',
            'translateVoice',
            'getNetworkType',
            'openLocation',
            'getLocation',
            'hideOptionMenu',
            'showOptionMenu',
            'hideMenuItems',
            'showMenuItems',
            'hideAllNonBaseMenuItem',
            'showAllNonBaseMenuItem',
            'closeWindow',
            'scanQRCode',
            'chooseWXPay',
            'openProductSpecificView',
            'addCard',
            'chooseCard',
            'openCard',
            'updateAppMessageShareData',
            'updateTimelineShareData',
            'getLocalImgData'
          ]
        })
        wx.error(res => {
          console.error(res)
          console.log('WxConfig验证失败')
        })
        wx.ready(() => {
          // wx.startRecord({})
          // setTimeout(function(){
          //   wx.stopRecord({})
          // },500)
        })
      })
    },
    //获取列表
    fngetconverlist(){
      var self = this;
      var groupList={};
      apiplanprocess({
        profile_id: localStorage.getItem('profileId'),
        token: localStorage.getItem('token'),
      }).then(res02 => {
        console.log(">>>>>>>")
        console.log(res02)
        var planjson={};
        if(res02.data instanceof Array){
          for(let j=0;j<res02.data.length;j++){
            planjson[res02.data[j].imGroupId]=res02.data[j];
          }
        }
 
        console.log('planjson')
        console.log(planjson)
        apiGetGroupList({
          profileId: localStorage.getItem('profileId'),
          token: localStorage.getItem('token'),
          pageNo: 1,
          pageSize: 1000,
          // encryptLevel: 1
        }).then(res => {
          console.log('apiGetGroupList')
          console.log(res)
          if(res.status == 200){
            if(!res.data.recordList){
              res.data.recordList=[];
            }
            var data02=res.data.recordList;
            for(let i=0;i<data02.length;i++){
              if(planjson[data02[i].campGroupId]){
                data02[i].totalDay=planjson[data02[i].campGroupId].period;
                data02[i].nowDay=planjson[data02[i].campGroupId].current;
              }else{
                data02[i].totalDay=data02[i].totalServiceDay;
                data02[i].nowDay=data02[i].currentDay;
              }
              // data02[i].starDay=data02[i].startDateTime||self.nowtime
              // data02[i].endDay=data02[i].endDateTime||self.nowtime
              // data02[i].totalDay=changetime((data02[i].endDay-data02[i].starDay),6)+1;
              // if(data02[i].serviceStatus==1){
              //   data02[i].nowDay=changetime((self.nowtime-data02[i].starDay),6)+1;
              // }else if(data02[i].serviceStatus==0){
              //   data02[i].nowDay=0;
              // }else if(data02[i].serviceStatus==2){
              //   data02[i].nowDay=data02[i].totalDay;
              // }
              groupList['GROUP'+data02[i].campGroupImName]=data02[i];
            }
            apiGetC2CList({
              profileId: localStorage.getItem('profileId'),
              token: localStorage.getItem('token'),
              pageNo: 1,
              pageSize: 100
            }).then(res => {
              if(res.status == 200){

                if(!res.data.recordList){
                  res.data.recordList=[];
                }
                for(let i=0;i<res.data.recordList.length;i++){
                  if(!res.data.recordList[i].mgrIdentityType){
                    res.data.recordList[i].mgrIdentityType=1;
                  }
                  if(!groupList['C2C'+res.data.recordList[i].healthManagerImAccount]||groupList['C2C'+res.data.recordList[i].healthManagerImAccount].serviceStatus==2){
                    groupList['C2C'+res.data.recordList[i].healthManagerImAccount]=res.data.recordList[i];
                  }
                }
                self.$store.commit('upConverList02',groupList)
                self.$store.commit('updateConversationList',self.conversationList)


              }else{
                self.$toast(res.msg);
              }
            })
            // console.log(">>>>>>>list>>>>>>>>>>")
            //  console.log(">>>>>>>list>>>>>>>>>>")
            console.log(groupList)
            // self.$store.commit('upConverList02',groupList)
          }else{
            self.$toast(res.msg);
          }
        })
      })
    },
    //补全默认会话列表--暂时不用--改为在store里面补全
    fnCompleteConver(arr){
      if(this.isSDKReady){
        this.$store.dispatch(
          'checkoutConversation',
          'conversationid'
        )
        this.$store.commit('removeAtmeMesssage',conversationid)
      }else{
        setTimeout(function(){
          fnCompleteConver(arr)
        },200)
      }
    },
    //进去私聊
    fnmessageConversation(type,ugid){
      if(!type){
        type=1
      }
      var self = this;
      if(self.isSDKReady){
        if(ugid){
          if(type==1){
            self.$setCookie('gochat',1)
            self.$router.push({
              path: '/im/chat',
              query: {
                conversationid: `C2Chm_${ugid}`
              }
            })
          }
        }else{
          // self.$router.push({url:'/im/index'})
        }
      }else{
        setTimeout(function(){
          self.fnmessageConversation(type,ugid)
        },500)
      }
    },
    fnCwiLogin() {
      var self = this
      apiGetsig({
        appId: this.cwiappid,
        profileId: this.profileId,
        token: this.token,
      }).then(res =>{
        if (res.status==200) {
          self.$store.commit('uploadNohasim','')
          self.$setCookie('userID',res.data.userId)
          self.$setCookie('userSig',res.data.userSig)
          self.tokenlogin(res.data.userId,res.data.userSig)
        } else {
          self.$store.commit('uploadNohasim',1)
          // self.$toast(res.msg)
        }
      })
    },
    tokenlogin(userID,userSig) {
      this.tim.login({
        userID: userID,
        userSig: userSig
      }).then(() => {
        this.$store.commit('toggleIsLogin', true)
        this.$store.commit('startComputeCurrent')
        this.$store.commit({
          type: 'GET_USER_INFO',
          userID: userID,
          userSig: userSig,
          sdkAppID: window.genTestUserSig('').SDKAppID
        })
        console.log('IM～登录成功')
        console.log('wag--1-1-1-1-1--1-1-1-1-1-1-1');
        this.fngetconverlist();
      }).catch(error => {
        console.log("IM～登录失败",error)
        // self.$store.dispatch('logout')
      })
    },
    initListener() {
      // 登录成功后会触发 SDK_READY 事件，该事件触发后，可正常使用 SDK 接口
      this.tim.on(this.TIM.EVENT.SDK_READY, this.onReadyStateUpdate, this)
      // SDK NOT READT
      this.tim.on(this.TIM.EVENT.SDK_NOT_READY, this.onReadyStateUpdate, this)
      // 被踢出
      this.tim.on(this.TIM.EVENT.KICKED_OUT, this.onKickOut)
      // SDK内部出错
      this.tim.on(this.TIM.EVENT.ERROR, this.onError)
      // 收到新消息
      this.tim.on(this.TIM.EVENT.MESSAGE_RECEIVED, this.onReceiveMessage)
      // 会话列表更新
      this.tim.on(this.TIM.EVENT.CONVERSATION_LIST_UPDATED, this.onUpdateConversationList)
      // 群组列表更新
      this.tim.on(this.TIM.EVENT.GROUP_LIST_UPDATED, this.onUpdateGroupList)
      // 网络监测
      this.tim.on(this.TIM.EVENT.NET_STATE_CHANGE, this.onNetStateChange)


    },
    onReceiveMessage({ data: messageList }) {
      console.log("收到新消息",messageList)
      var servicemsg = {};
      try{
        for(var i=0;i<messageList.length;i++){
          if(messageList[i].conversationID == this.servicemsgId||messageList[i].conversationID == this.servicemsgId02){
            servicemsg = messageList[i];
            messageList.splice(i,1);
          }
        }
      }catch(e){console.log(e)}
      if(messageList.length==0){
        if(servicemsg.conversationID){
          this.tim.getConversationList()
        }
        return ;
      }
      this.handleVideoMessage(messageList)
      this.handleAt(messageList)
      this.handleQuitGroupTip(messageList)
      this.$store.commit('pushCurrentMessageList', messageList)
    },
    onError({ data }) {
      if (data.message !== 'Network Error') {
        this.$store.commit('showMessage', {
          message: data.message,
          type: 'error'
        })
      }
    },
    onReadyStateUpdate({ name }) {
      const isSDKReady = name === this.TIM.EVENT.SDK_READY ? true : false
      this.$store.commit('toggleIsSDKReady', isSDKReady)

      if (isSDKReady) {
        this.tim
          .getMyProfile()
          .then(({ data }) => {
            this.$store.commit('updateCurrentUserProfile', data)
          })
          .catch(error => {
            this.$store.commit('showMessage', {
              type: 'error',
              message: error.message
            })
          })
        this.$store.dispatch('getBlacklist')
      }
    },
    kickedOutReason(type) {
      switch (type) {
        case this.TIM.TYPES.KICKED_OUT_MULT_ACCOUNT:
          return '由于多实例登录'
        case this.TIM.TYPES.KICKED_OUT_MULT_DEVICE:
          return '由于多设备登录'
        case this.TIM.TYPES.KICKED_OUT_USERSIG_EXPIRED:
          return '由于 userSig 过期'
        default:
          return ''
      }
    },
    checkoutNetState(state) {
      switch (state) {
        case this.TIM.TYPES.NET_STATE_CONNECTED:
          return { message: '已接入网络', type: 'success' }
        case this.TIM.TYPES.NET_STATE_CONNECTING:
          return { message: '当前网络不稳定', type: 'warning' }
        case this.TIM.TYPES.NET_STATE_DISCONNECTED:
          return { message: '当前网络不可用', type: 'error' }
        default:
          return ''
      }
    },
    onNetStateChange(event) {
      this.$store.commit('showMessage', this.checkoutNetState(event.data.state))
    },
    onKickOut(event) {
      this.$store.commit('showMessage', {
        message: `${this.kickedOutReason(event.data.type)}被踢出，请重新登录。`,
        type: 'error'
      })
      this.$removeCookie('htoken')
      this.$removeCookie('hpid')
      this.$removeCookie('userID')
      this.$removeCookie('userSig')
      this.$store.commit('toggleIsLogin', false)
      this.$store.commit('reset')
    },
    onUpdateConversationList(event) {
      var servicemsg = {};
      try{
        for(var i=0;i<event.data.length;i++){
          if(event.data[i].conversationID == this.servicemsgId||event.data[i].conversationID == this.servicemsgId02){
            servicemsg = event.data[i];
            event.data.splice(i,1);
          }
        }
      }catch(e){console.log(e)}
      this.$store.commit('updateServicemsg', servicemsg)
      this.$store.commit('updateConversationList', event.data)
    },
    onUpdateGroupList(event) {
      this.$store.commit('updateGroupList', event.data)
    },
    onReceiveGroupSystemNotice(event) {
      const isKickedout = event.data.type === 4
      const isCurrentConversation =
        `GROUP${event.data.message.payload.groupProfile.groupID}` ===
        this.currentConversation.conversationID
      // 在当前会话被踢，需reset当前会话
      if (isKickedout && isCurrentConversation) {
        this.$store.commit('resetCurrentConversation')
      }
      Notification({
        title: '新系统通知',
        message: translateGroupSystemNotice(event.data.message),
        duration: 3000,
        onClick: () => {
          const SystemConversationID = '@TIM#SYSTEM'
          this.$store.dispatch('checkoutConversation', SystemConversationID)
        }
      })
    },
    /**
     * 处理 @ 我的消息
     * @param {Message[]} messageList
     */
    handleAt(messageList) {
      // 筛选有 @ 符号的文本消息
      const atTextMessageList = messageList.filter(
        message =>
          message.type === this.TIM.TYPES.MSG_TEXT &&
          message.payload.text.includes('@')
      )
      for (let i = 0; i < atTextMessageList.length; i++) {
        const message = atTextMessageList[i]
        // @ 我的
        if (this.atjudge(message.payload.text)) {
          // 当前页面不可见时，调用window.Notification接口，系统级别通知。
          if (this.$store.getters.hidden) {
            this.notifyMe(message)
          }
          try{
            Notification({
              title: `有人在群${message.conversationID.slice(5)}@了你`,
              message: message.payload.text,
              duration: 3000
            })
          }catch(e){}
          this.$store.commit('uploadAtmeMesssage',message.conversationID)
          // this.$bus.$emit('new-messsage-at-me', {
          //   data: { conversationID: message.conversationID }
          // })
        }
      }
      //兼容客户端艾特用户
      // const atTextMessageList02 = messageList.filter(
      //   message => message.type === this.TIM.TYPES.MSG_CUSTOM &&JSON.parse(message.payload.data).info
      // )
      // for(let i = 0; i < atTextMessageList02.length; i++){
      //   const message = atTextMessageList02[i]
      //   try{
      //     if(message.type == this.TIM.TYPES.MSG_CUSTOM&&JSON.parse(message.payload.data).info){
      //       var arrinfo = JSON.parse(message.payload.data).info
            
      //       var atjudge = false
      //       for(var j=0;j<arrinfo.length;j++){
      //         if(arrinfo[j].identity == this.userID){
      //           atjudge = true
      //           break 
      //         }
      //       }
      //       if (atjudge) {
      //         // 当前页面不可见时，调用window.Notification接口，系统级别通知。
      //         if (this.$store.getters.hidden) {
      //           this.notifyMe(message)
      //         }
      //         Notification({
      //           title: `有人在群${message.conversationID.slice(5)}提到了你`,
      //           message: JSON.parse(message.payload.data).content,
      //           duration: 3000
      //         })
      //         this.$bus.$emit('new-messsage-at-me', {
      //           data: { conversationID: message.conversationID }
      //         })
      //       }
      //     }
          
      //   }catch(e){console.log(e)}
      // }
    },
    atjudge(message) {
      if(message.indexOf(`@${this.currentUserProfile.userID} `)>=0||message.indexOf(`@${this.currentUserProfile.nick} `)>=0){
        return true;
      }
      var atidnum = message.indexOf(`@${this.currentUserProfile.userID}`)
      var atnamenum = message.indexOf(`@${this.currentUserProfile.userID}`)
      if(atidnum>=0&&message.length==(this.currentUserProfile.userID.length+atidnum+1)){
        return true;
      }
      if(atnamenum>=0&&message.length==(this.currentUserProfile.nick.length+atnamenum+1)){
        return true;
      }
      return false
    },
    selectConversation(conversationID) {
      if (conversationID !== this.currentConversation.conversationID) {
        this.$store.dispatch('checkoutConversation',conversationID)
      }
    },
    isJsonStr(str) {
      try{
        JSON.parse(str)
        return true
      }catch {
        return false
      }
    },
    handleVideoMessage(messageList) {
      const videoMessageList = messageList.filter(
        message => message.type === this.TIM.TYPES.MSG_CUSTOM && this.isJsonStr(message.payload.data)
      )
      if (videoMessageList.length === 0) return
      const videoPayload = JSON.parse(videoMessageList[0].payload.data)
      if (videoPayload.action === ACTION.VIDEO_CALL_ACTION_DIALING) {
        if (this.isBusy) {
          this.$bus.$emit('busy', videoPayload, videoMessageList[0])
          return
        }
        this.$store.commit('GENERATE_VIDEO_ROOM', videoPayload.room_id)
        this.selectConversation(videoMessageList[0].conversationID) // 切换当前会话页
        if (videoMessageList[0].from !== this.userID) {
          this.$bus.$emit('isCalled')
        }
      }
      if (videoPayload.action === ACTION.VIDEO_CALL_ACTION_SPONSOR_CANCEL) {
        this.$bus.$emit('missCall')
      }
      if (videoPayload.action === ACTION.VIDEO_CALL_ACTION_REJECT) {
        this.$bus.$emit('isRefused')
      }
      if (videoPayload.action === ACTION.VIDEO_CALL_ACTION_SPONSOR_TIMEOUT) {
        this.$bus.$emit('missCall')
      }
      if (videoPayload.action === ACTION.VIDEO_CALL_ACTION_ACCEPTED) {
        this.$bus.$emit('isAccept')
      }
      if (videoPayload.action === ACTION.VIDEO_CALL_ACTION_HANGUP) {
        this.$bus.$emit('isHungUp')
      }
      if (videoPayload.action === ACTION.VIDEO_CALL_ACTION_LINE_BUSY) {
        this.$bus.$emit('isRefused')
      }
      if (videoPayload.action === ACTION.VIDEO_CALL_ACTION_ERROR) {
        this.$bus.$emit('isRefused')
      }
    },
    /**
     * 使用 window.Notification 进行全局的系统通知
     * @param {Message} message
     */
    notifyMe(message) {
      // 需检测浏览器支持和用户授权
      if (!('Notification' in window)) {
        return
      } else if (window.Notification.permission === 'granted') {
        this.handleNotify(message)
      } else if (window.Notification.permission !== 'denied') {
        window.Notification.requestPermission().then(permission => {
          // 如果用户同意，就可以向他们发送通知
          if (permission === 'granted') {
            this.handleNotify(message)
          }
        })
      }
    },
    handleNotify(message) {
      const notification = new window.Notification('有人提到了你', {
        icon: 'https://webim-1252463788.file.myqcloud.com/demo/img/logo.dc3be0d4.png',
        body: message.payload.text
      })
      notification.onclick = () => {
        window.focus()
        this.$store.dispatch('checkoutConversation', message.conversationID)
        notification.close()
      }
    },
    handleLinkClick() {
      MTA.clickStat('link_two', { click: 'true' })
    },
    /**
     * 收到有群成员退群/被踢出的groupTip时，需要将相关群成员从当前会话的群成员列表中移除
     * @param {Message[]} messageList
     */
    handleQuitGroupTip(messageList) {
      // 筛选出当前会话的退群/被踢群的 groupTip
      const groupTips = messageList.filter(message => {
        return this.currentConversation.conversationID === message.conversationID &&
          message.type === this.TIM.TYPES.MSG_GRP_TIP &&
          (message.payload.operationType === this.TIM.TYPES.GRP_TIP_MBR_QUIT ||
          message.payload.operationType === this.TIM.TYPES.GRP_TIP_MBR_KICKED_OUT)
      })
      // 清理当前会话的群成员列表
      if (groupTips.length > 0) {
        groupTips.forEach(groupTip => {
          if (Array.isArray(groupTip.payload.userIDList) || groupTip.payload.userIDList.length > 0) {
            this.$store.commit('deleteGroupMemberList', groupTip.payload.userIDList)
          }
        })
      }
    }
  }
}
</script>

<style lang="scss">
.container{
  height: 100%;
  width: 100%;
  overflow: hidden;
  .class-iphone{
    width: 100%;
    height: 100%;
    overflow: hidden;
  }
  &.isNewTab{
    padding-bottom: 1.306667rem;
    // padding-bottom: 2rem;
    &.isIphoneX{
      .class-iphone{
        padding-bottom: 28px;
        padding-bottom: constant(safe-area-inset-bottom);
        padding-bottom: env(safe-area-inset-bottom);
      }
    }
  }
}

</style>
